package com.pudding.service.impl;

import com.pudding.entity.po.TbExcel;
import com.pudding.mapper.ExcelMapper;
import com.pudding.service.InitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
@RequiredArgsConstructor
@Slf4j
public class InitServiceImpl implements InitService {

    private final ExcelMapper excelMapper;

    /**
     * 初始化数据库10000条数据
     */
    @Override
    public void init() {
        ArrayList<TbExcel> list = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < 10000; i++) {
            list.add(new TbExcel("字符串" + i, new BigDecimal(i), now));
        }

        excelMapper.insertBatch(list);
    }

    @Override
    public void init2() {
        LocalDateTime now = LocalDateTime.now();
        // 通过计数器/信号量来计数判断线程是否执行完
        CountDownLatch countDownLatch = new CountDownLatch(100);

        // 开启100个虚拟线程，每个线程执行10000条数据
        for (int i = 0; i < 100; i++) {
            // 开启虚拟线程（JDK21新增）
            Thread.ofVirtual().start(() -> {
                List<TbExcel> list = new ArrayList<>();
                for (int j = 0; j < 10000; j++) {
                    list.add(new TbExcel("字符串" + j, new BigDecimal(j), now));
                }
                excelMapper.insertBatch(list);  //注意mysql连接的url的写法，必须开启批量处理

                // 计数器减一
                countDownLatch.countDown();
                log.info("线程{}执行完毕", Thread.currentThread().getName());
            });
        }

        // 是否结束
        try {
            countDownLatch.await(); //让主线程等待虚拟线程执行完成
            log.info("初始化完成");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
